//
//  overworkingViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/24.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "chaxunjinqi.h"

#import "overworkingViewController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "detailViewController.h"
#define  KToarchivebPagdMethod @"toarchivePage" //待办 分页列表


@interface overworkingViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)NSInteger totalCounts; //总条数

@property(nonatomic,copy)NSString * searchText;
@end

@implementation overworkingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
       [backImageView setImage:[UIImage imageNamed:@"近期经办背景"]];
self.tableView.backgroundView = backImageView;
        self.tableView.delegate = self;
    self.tableView.dataSource =self;
[self setRightItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
    [self.tableView addHeaderWithCallback:^{
        self.currentPage = 1;
 if (_isSearching) {
    [self loadSearchData];

}else{
[self loadData];
 }

    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
               if (_isSearching) {
    [self loadSearchMore];

}else{
[self loadMore];
 }

        }else{
        
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
    
        }
       
    }];
}
 -(void)loadSearchData{
   
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":_text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
//    [HttpTools requestWithURL:@"exchSearch" arrays:array method:method success:^(id JSON) {
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {

        if (self.currentPage == 1) {
            [self.dataArray removeAllObjects];
        }
    [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}

-(void)setRightItem{
            UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;
   
    
}
#pragma mark 搜素
-(void)searchAction{
    
    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                 chaxunjinqi *vc = [[chaxunjinqi alloc]init];

                _text = textField.text;
//                [self.dataArray removeAllObjects];
//                self.isSearching = YES;
                self.currentPage = 1;
                vc.text = _text;
                vc.string = _string;
                if ([_string isEqualToString:@"已办发文(流转中)"]){
                vc.db = @"ybfw";
                                }
                else if ([_string isEqualToString:@"已办收文(流转中)"]){
                                vc.db = @"ybsw";

                } else if ([_string isEqualToString:@"已办发文(已归档)"]){
                                vc.db = @"ybgdfw";

                } else{
                                vc.db = @"ybgdsw";

                }
                vc.xqmethod = _method;
//                _dataArray = nil;
                [self.navigationController pushViewController:vc animated:YES];
//                [self loadSearchData:textField.text];
            }
            
        }
        
    }];
    
}
//搜索内容加载更多
- (void)loadSearchMore
{
     NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":_text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
//    [HttpTools requestWithURL:@"exchSearch" arrays:array method:method success:^(id JSON) {
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {

        if (self.currentPage == 1) {
            [self.dataArray removeAllObjects];
        }
    [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}


#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
      _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:[NSString stringWithFormat:@"暂时还没有%@哦",_string]];
   
        }
    } failure:^(NSError *error) {
     [self.tableView headerEndRefreshing];
        
    }];
 
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
   // NSLog(@"-------%@",JSON);
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            GDataXMLElement * yearElement = [[data elementsForName:@"dbpath"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.year = [yearElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    if (_isSearching) {
    self.title = [NSString stringWithFormat:@"近期经办(%lu)",self.totalCounts];
}else{
     self.title = [NSString stringWithFormat:@"%@(%lu)",_string,self.totalCounts];
   }
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UnDoneModel * model = self.dataArray[indexPath.row];
    CGFloat  titleFloat  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    NSString * desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    CGFloat desFloat = [OAToolBox sizebyText:desstring font:14 minsWidth:80];
    return  titleFloat + desFloat + 20;
//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
                    cell.backgroundColor=[UIColor clearColor];//关键语句  

    UnDoneModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UnDoneModel * model = self.dataArray[indexPath.row];
detailViewController * detailVC = (detailViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = model.fileId;
if(_isSearching){

   detailVC.type =@"chaxun";
   detailVC.yearstring = model.year;
}



else if ([_method isEqualToString:@"toybFwPage"]||[_method isEqualToString:@"toybSwPage"]) {
    detailVC.type = @"work1";
}
else {
detailVC.type = @"work2";

}




[self.navigationController pushViewController:detailVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
